package com.cmcm.network;

import com.android.build.api.transform.DirectoryInput;
import com.android.build.api.transform.Format;
import com.android.build.api.transform.JarInput;
import com.android.build.api.transform.QualifiedContent;
import com.android.build.api.transform.Transform;
import com.android.build.api.transform.TransformException;
import com.android.build.api.transform.TransformInput;
import com.android.build.api.transform.TransformInvocation;
import com.android.build.api.transform.TransformOutputProvider;
import com.android.build.gradle.internal.pipeline.TransformManager;

import org.apache.commons.io.FileUtils;
import org.gradle.api.Project;
import org.gradle.api.logging.Logger
import org.gradle.api.tasks.compile.JavaCompile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Set;

/**
 * Created by suj on 17-1-3.
 */

public class NetTrans extends Transform {

    Project mProject;
    String mAjPath;
    String tagetCompatAbility ="1.7";
    String sourceCompatAbility ="1.7";


    public void setClassPath(String classPath) {
        mClassPath = classPath;
    }

    String mClassPath ;

    public NetTrans(Project project){
        mProject = project;
        mAjPath= project.project(":aoplib").getProjectDir().getAbsolutePath()+File.separator+"src"+File.separator+"main"+File.separator+"java"+File.separator+"com"+File.separator+"cmcm"+File.separator+"aoplib";
        project.afterEvaluate {
            configuration.variants.all { variant ->
                JavaCompile javaCompile = variant.hasProperty('javaCompiler') ? variant.javaCompiler : variant.javaCompile
                encoding = javaCompile.options.encoding
                bootClassPath = configuration.bootClasspath.join(File.pathSeparator)
                sourceCompatibility = javaCompile.sourceCompatibility
                targetCompatibility = javaCompile.targetCompatibility
            }
        }

    }

    public static final String NET_TRANS = "NetTrans";

    @Override
    public String getName() {
        return NET_TRANS;
    }

    @Override
    public Set<QualifiedContent.ContentType> getInputTypes() {
        return ImmutableSet.<QualifiedContent.ContentType>of(QualifiedContent.DefaultContentType.CLASSES)
    }

    @Override
    public Set<QualifiedContent.Scope> getScopes() {
        return ImmutableSet.<QualifiedContent.Scope>of(QualifiedContent.Scope.PROJECT
                , QualifiedContent.Scope.PROJECT_LOCAL_DEPS
                , QualifiedContent.Scope.EXTERNAL_LIBRARIES
                , QualifiedContent.Scope.SUB_PROJECTS
                , QualifiedContent.Scope.SUB_PROJECTS_LOCAL_DEPS)
    }



    @Override
    public boolean isIncremental() {
        return false;
    }

    @Override
    public void transform(TransformInvocation transformInvocation) throws TransformException, InterruptedException, IOException {
        super.transform(transformInvocation);
        // 包装了一层东西而已，还是用这个玩意高一下吧
        mProject.getLogger().error("start to transform");
        System.out.println("do ...................");
        Logger logger = mProject.getLogger();
        Collection<TransformInput> inputs = transformInvocation.getInputs();
        logger.error(Arrays.toString(inputs.toArray()));
        for (TransformInput input:inputs){
            Collection<DirectoryInput> directoryInputs = input.getDirectoryInputs();
            handleDirectoryInputs(directoryInputs,transformInvocation.getOutputProvider());
            Collection<JarInput> jarInputs = input.getJarInputs();
            handleJarInputs(jarInputs,transformInvocation.getOutputProvider());

        }

    }


    private boolean isInputEmpty(Collection<?> jarInputs){
        if (jarInputs==null){
            return true;
        }
        if (jarInputs.isEmpty()){
            return true;
        }
        return false;
    }


    private void handleJarInputs(Collection<JarInput> jarInputs, TransformOutputProvider outputProvider) throws IOException {
        boolean inputEmpty = isInputEmpty(jarInputs);
        if (!inputEmpty){
            // interator
            for (JarInput jarInput:jarInputs){
                handleSingleJarInput(jarInput,outputProvider);
            }
        }
    }

    private void handleSingleJarInput(JarInput jarInput, TransformOutputProvider outputProvider) throws IOException {
        String jarNameNew = jarInput.getName()+System.currentTimeMillis();
        File contentLocation = outputProvider.getContentLocation(jarNameNew, jarInput.getContentTypes(), jarInput.getScopes(), Format.JAR);
        if (SafetyFilter.isSafety(jarInput.getFile())){
            FileUtils.copyFile(jarInput.getFile(),contentLocation);

            return;
        }
        JarAspectHandler handler = createHandler(jarInput, contentLocation)
        handler.handle();
    }

    /***
     *
     *
     *
     *for (TransformInput transformInput : inputs) {
     for (DirectoryInput directoryInput : transformInput.directoryInputs) {

     println "directoryInput:::${directoryInput.file.absolutePath}"

     aspectWork.aspectPath << directoryInput.file
     aspectWork.inPath << directoryInput.file
     aspectWork.classPath << directoryInput.file
     }

     for (JarInput jarInput : transformInput.jarInputs) {

     aspectWork.aspectPath << jarInput.file
     aspectWork.classPath << jarInput.file

     String jarPath = jarInput.file.absolutePath
     if (isIncludeFilterMatched(jarPath, includeJarFilter)
     && !isExcludeFilterMatched(jarPath, excludeJarFilter)) {
     println "includeJar:::${jarPath}"
     aspectWork.inPath << jarInput.file
     } else {
     println "excludeJar:::${jarPath}"
     copyJar(outputProvider, jarInput)
     }
     }
     }
     */

    private JarAspectHandler createHandler(JarInput jarInput, File contentLocation) {
        JarAspectHandler handler = new JarAspectHandler(mProject);
        handler.setInputPath(jarInput.getFile().getAbsolutePath());
        handler.setClassPath(mClassPath);
        // 这个名字采取tricky method

        handler.setOutPath(contentLocation.getAbsolutePath());
        handler
    }

    private void handleDirectoryInputs(Collection<DirectoryInput> directoryInputs, TransformOutputProvider outputProvider) throws IOException {
        boolean inputEmpty = isInputEmpty(directoryInputs);
        if (!inputEmpty){
            // interator
            for (DirectoryInput directoryInput:directoryInputs){
                handleSingleDirectory(directoryInput,outputProvider);
            }
        }
    }

    private void handleSingleDirectory(DirectoryInput directoryInput, TransformOutputProvider outputProvider) throws IOException {
        mProject.getLogger().error(directoryInput.toString());
        String jarNameNew = directoryInput.getName()+System.currentTimeMillis();
        File contentLocation = outputProvider.getContentLocation(jarNameNew, directoryInput.getContentTypes(), directoryInput.getScopes(), Format.DIRECTORY);
        if (SafetyFilter.isSafety(directoryInput.getFile())){
            FileUtils.copyDirectory(directoryInput.getFile(),contentLocation);
            return;
        }

        JarAspectHandler handler = new JarAspectHandler(mProject);
        handler.setAjPath(mAjPath);
        handler.setInputPath(directoryInput.getFile().getAbsolutePath());
        handler.setClassPath(mClassPath);
        // 这个名字采取tricky method
        handler.setOutPath(contentLocation.getAbsolutePath());
        handler.handle();
    }


}
